<template>
  <div>
    <page-main>
      <el-row>
        <el-col :span="6" style="display: flex;">
          <span style="margin-right: 10px; width: 60px; line-height: 40px;">攀枝花:</span>
          <el-cascader
            style="width: 300px;"
            :props="defaultProps"
            filterable
            :options="unitList"
            clearable
            v-model="searchForm.unit_id"
          ></el-cascader>
        </el-col>
        <el-col :span="4" style="display: flex;">
          <span style="line-height: 40px; margin-left: 10px; width: 80px;">用户名:</span>
          <el-input v-model="searchForm.username" clearable placeholder="请输入用户名"></el-input>
        </el-col>
        <el-col :span="3" style="display: flex;">
          <span style="line-height: 40px; margin-left: 10px; width: 60px;">姓名:</span>
          <el-input v-model="searchForm.name" clearable placeholder="请输入姓名"></el-input>
        </el-col>
        <el-col :span="4" style="display: flex;">
          <span style="line-height: 40px; margin-left: 10px; width: 50px;">角色:</span>
          <el-select v-model="searchForm.role_id" filterable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.role_name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" style="margin-left: 10px;" @click="searchBtn">搜索</el-button>
          <el-button type="warning" @click="refreshBtn">重置</el-button>
        </el-col>
      </el-row>
    </page-main>
    <page-main>
      <!-- <el-button
              size="mini"
              type="primary"
              @click="dialogFormVisible = true">添加</el-button> -->
      <el-table
        :data="
          tableData.filter(
            (data) => !search || data.name.toLowerCase().includes(search.toLowerCase())
          )
        "
        :default-sort="{ prop: 'id', order: 'descending' }"
      >
        <el-image src="/public/pwa_icons/192x192.png"></el-image>
        <el-table-column width="60" label="id" prop="id" sortable></el-table-column>
        <!-- <el-table-column label="头像" prop="head_img">
          <template #default="scope">
            <el-popover placement="right" :width="100" trigger="hover">
              <el-image :src="scope.row.head_img"></el-image>
              <template #reference>
                <el-image style="width: 100px;" :src="'http://www.jingxiaocheng.cn' + scope.row.head_img"></el-image>
              </template>
            </el-popover>
          </template>
        </el-table-column> -->
        <el-table-column label="用户名" prop="username"> </el-table-column>
        <el-table-column label="姓名" prop="name"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="手机号" prop="phone"> </el-table-column>
        <el-table-column label="区域" prop="region_name"> </el-table-column>
        <el-table-column label="所属单位" prop="unit_name"> </el-table-column>
        <el-table-column label="巡查记录">
          <template #default="scope">
            <el-button type="primary" @click="showPatrolRecord(scope.row)" size="mini"
              >详情</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="巡查轨迹图">
          <template #default="scope">
            <el-button type="primary" @click="showPatrolMap(scope.row)" size="mini">详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="查看详情">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="lookDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #header>
            <el-button size="mini" type="primary" @click="dialogFormVisible = true">添加</el-button>
          </template>
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-popconfirm
              confirm-button-text="删除"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除？"
              @confirm="del(scope.row)"
              @cancel="cancelEvent"
            >
              <template #reference>
                <el-button size="mini" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          :current-page="pagination.page"
          :total="total"
          :page-size="pagination.size"
          :page-sizes="pagination.sizes"
          :layout="pagination.layout"
          :hide-on-single-page="false"
          class="pagination"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
      <!-- <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          v-model:currentPage="tableDataInfo.page"
          :page-count="tableDataInfo.total_page"
          layout="prev, pager, next, jumper"
          :hide-on-single-page="true"
        >
        </el-pagination>
      </div> -->
    </page-main>
    <el-dialog
      v-model="dialogFormVisible"
      width="60%"
      @close="closeDialog"
      :close-on-click-modal="false"
      :title="title"
    >
      <el-form ref="childForm" :rules="rules" :model="formData" :disabled="disabled">
        <el-row>
          <!-- 社会单位选择 -->
          <el-col :span="6" :offset="1">
            <el-form-item label="社会单位选择" prop="unit_id">
              <el-select v-model="formData.unit_id" filterable placeholder="请选择">
                <el-option
                  v-for="item in societyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="类型" prop="type">
              <el-select v-model="formData.type" filterable placeholder="请选择">
                <el-option
                  v-for="item in userTypeList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="用户名/手机号" prop="username">
              <el-input
                v-model="formData.username"
                :maxlength="18"
                oninput="value=value.replace(/[^a-zA-Z0-9]/g,'')"
                :disabled="title == '编辑'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="formData.password"
                show-password
                :maxlength="18"
                oninput="value=value.replace(/[^a-zA-Z0-9_]/g,'')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="角色" prop="role_id">
              <el-select v-model="formData.role_id" filterable placeholder="请选择">
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.role_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
                <!-- <el-radio label="3">保密</el-radio> -->
              </el-radio-group>
              <!-- <el-select v-model="formData.sex" placeholder="请选择">
                <el-option
                  v-for="item in sexLists"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="formData.phone"
                oninput="value=value.replace(/[^\d]/g,'')"
                :maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6" :offset="1">
            <el-form-item label="头像" prop="head_img">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                list-type="picture-card"
                :headers="upLoadImgHeader"
                :data="upLoadImgData"
                :on-success="headImgUpSuccess"
                limit="1"
                class="img"
                :before-remove="imgRemove"
                :on-change="imgChange"
                accept=".jpg,.png,.jpeg"
                :file-list="imgFileList"
                :on-preview="handlePictureCardPreview"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="身份证" prop="card_no"
              ><el-input v-model="formData.card_no"></el-input
            ></el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="年龄" prop="age">
              <el-input
                v-model="formData.age"
                oninput="value=value.replace(/[^\d]/g,'')"
                :maxlength="2"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="岗位" prop="job">
              <el-input v-model="formData.job"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="QQ号" prop="qq">
              <el-input v-model="formData.qq" oninput="value=value.replace(/[^\d]/g,'')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="formData.status"
                active-text="启用"
                inactive-text="禁用"
                :active-value="1"
                :inactive-value="2"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" v-if="!disabled">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 图片放大 -->
    <el-dialog v-model="dialogVisible">
      <img style="width: 100%;" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import storage from '@/util/storage'
import { ElMessage } from 'element-plus'
// 分页
import paginationMixin from '@/mixins/pagination'
export default {
  // 分页
  mixins: [paginationMixin],
  data() {
    return {
      defaultProps: {
        children: 'sub_item',
        label: 'name',
        value: 'id',
        checkStrictly: true
      },
      unitList: [],
      searchForm: {
        role_id: '',
        username: '',
        role_name: '',
        unit_id: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      searchValue: '',
      total: 0,
      disabled: false,
      dialogFormVisible: false,
      tableData: [],
      search: '',
      tableDataInfo: '',
      imgFileList: [],
      formData: {
        type: '',
        username: '',
        password: '',
        role_id: '',
        name: '',
        sex: 1,
        phone: '',
        head_img: '',
        card_no: '',
        age: '',
        job: '',
        qq: '',
        user_type: '',
        status: 1,
        unit_id: ''
      },
      societyList: [],
      rules: {
        type: [{ required: true, message: '请选择', trigger: 'blur' }],
        username: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            trigger: 'blur',
            message: '用户名长度为6到18位'
          }
        ],

        role_id: [{ required: true, message: '请选择', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            min: 11,
            max: 11,
            trigger: 'blur',
            message: '请输入正确的手机号'
          }
        ],
        user_type: [{ required: true, message: '请选择', trigger: 'blur' }],
        status: [{ required: true, message: '请选择', trigger: 'blur' }],
        unit_id: [{ required: true, message: '请选择', trigger: 'blur' }]
      },
      id: '',
      unit_id: '', //单位id
      sexLists: [
        { name: '男', id: 1 },
        { name: '女', id: 2 },
        { name: '保密', id: 3 }
      ],
      typeList: [],
      roleList: [],
      userTypeList: [
        //   {label: '法人', value: 'legal'},
        //   {label: '负责人', value: 'manger'},
        //   {label: '联系人', value: 'contact'},
        //   {label: '安全管理人', value: 'Safety'},
        //   {label: '消防安全责任人', value: 'liable'},
        //   {label: '消费管理人', value: 'fire_control'},
        //   {label: '从业人员', value: 'practice'}
      ],
      upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
      upLoadImgData: {
        type: 'image'
      },
      title: '添加'
    }
  },
  created() {
    this.$api.get('/unit/Setting/userType').then((res) => {
      this.userTypeList = res.data
    })
    // this.unit_id = this.$route.params.id;
    this.getDataList()
    this.getSocietyList()
    this.getRoleList()
    this.getRegion()
  },
  computed: {
    upLoadImgHeader() {
      return {
        'A-Token': this.$store.state.user.a_token,
        'U-Token': this.$store.state.user.u_token
      }
    }
  },
  methods: {
    //   删除
    del(row) {
      row.status = -1
      console.log(row)
      this.$api.post('/unit/YjUser/Save', row).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    //   搜索
    searchBtn() {
      this.getDataList()
    },
    // 重置
    refreshBtn() {
      this.searchForm = {
        role_id: '',
        username: '',
        role_name: '',
        unit_id: ''
      }
      this.getDataList()
    },
    //   获取区域
    getRegion() {
      this.$api.get('/unit/Region/tree').then((res) => {
        this.regionList = res.data
        this.$api
          .post('/unit/UnitInformation/lists', {
            page: 1,
            rows: 9999
          })
          .then((val) => {
            res.data.forEach((item) => {
              item.sub_item.forEach((subItem) => {
                val.data.lists.forEach((userItem) => {
                  if (subItem.id == userItem.region_id) {
                    subItem.sub_item.push(userItem)
                  }
                })
              })
            })
            this.unitList = res.data
          })
      })
    },
    //   图片放大
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //   图片
    imgChange() {
      let img = document.getElementsByClassName('img')[0]
      img.children[1].style.display = 'none'
    },
    imgRemove() {
      let img = document.getElementsByClassName('img')[0]
      img.children[1].style.display = 'block'
    },
    // 获取社会单位列表
    getSocietyList() {
      let user_info = this.$store.state.user.user_info
      this.$api
        .post('/unit/UnitInformation/lists', {
          region_id: user_info.region_id,
          page: 1,
          rows: 9999
        })
        .then((res) => {
          this.societyList = res.data.lists
        })
    },
    // 获取角色列表
    getRoleList() {
      this.$api.get('/unit/YjUser/role?page=1&rows=9999').then((res) => {
        this.roleList = res.data.list
      })
    },
    headImgUpSuccess(e) {
      this.formData.head_img = e.data.result
    },
    closeDialog() {
      this.$refs.childForm.resetFields()
      let temp = this.formData
      //   for (let key in temp) {
      //     temp[key] = "";
      //   }
      ;(this.formData = {
        type: '',
        username: '',
        password: '',
        role_id: '',
        name: '',
        sex: 1,
        phone: '',
        head_img: '',
        card_no: '',
        age: '',
        job: '',
        qq: '',
        user_type: '',
        status: 1,
        unit_id: ''
      }),
        (this.id = '')
      this.disabled = false
      let img = document.getElementsByClassName('img')[0]
      img.children[1].style.display = 'block'
      this.imgFileList = []
      this.title = '添加'
      console.log(this.formData)
    },
    colTitle(row, column, cellValue, index, e) {
      if (e == 'danger_source') {
        let temp = ['', '公众', '监管机构', '维保单位', '社会单位']
        return temp[cellValue]
      } else if (e == 'status') {
        let temp = ['', '未整改', '待审核', '已整改']
        return temp[cellValue]
      }
    },
    getDataList(page) {
      //   let pageNum = 1;
      //   if (page) {
      //     pageNum = page;
      //   }
      let data = JSON.parse(JSON.stringify(this.searchForm))
      if (data.unit_id) {
        console.log(data.unit_id)
        // 如果长度为3,表示选择的单位,小于三表示选中的区域
        if (data.unit_id.length == 3) {
          data.unit_id = data.unit_id[data.unit_id.length - 1]
        } else {
          data.region_id = data.unit_id[data.unit_id.length - 1]
          data.unit_id = ''
        }
      }
      let params = {
        rows: this.pagination.size,
        page: this.pagination.page,
        ...data
      }
      this.$api.post('/unit/YjUser/Lists', params).then((res) => {
        this.tableData = res.data.list
        this.tableDataInfo = res.data
        this.total = res.data.total
      })
    },
    // 搜索
    searchInputList() {
      this.getDataList()
    },
    handleEdit(index, row) {
      this.title = '编辑'
      this.id = row.id
      this.formData = JSON.parse(JSON.stringify(row))
      this.formData.unit_id = parseInt(this.formData.unit_id)
      if (!this.formData.age) this.formData.age = ''
      this.dialogFormVisible = true
      if (row.head_img) {
        this.imgFileList = [{ url: this.upDataUrl + row.head_img }]
        setTimeout(() => {
          let img = document.getElementsByClassName('img')[0]
          img.children[1].style.display = 'none'
        }, 100)
      }
    },
    // 查看详情
    lookDetails(row) {
      this.disabled = true
      this.id = row.id
      this.formData = JSON.parse(JSON.stringify(row))
      this.formData.sex = this.formData.sex + ''
      this.dialogFormVisible = true
      if (row.head_img) {
        this.imgFileList = [{ url: this.upDataUrl + row.head_img }]
        setTimeout(() => {
          let img = document.getElementsByClassName('img')[0]
          img.children[1].style.display = 'none'
        }, 100)
      }
    },
    handleSizeChange(e) {},
    handleCurrentChange(e) {
      this.getDataList(e)
    },
    submitForm() {
      this.$refs.childForm.validate((valid) => {
        if (valid) {
          let data = this.formData
          if (this.id) {
            data.id = this.id
          } else {
            data.id = 0
          }
          this.$api.post('/unit/YjUser/Save', data).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: res.msg
              })
              this.getDataList()
              this.dialogFormVisible = false
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        } else {
          ElMessage.error('请填写完整')
          return false
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.block {
    display: flex;
    justify-content: center;
    margin-top: 10px;
}
.searchBox {
    display: flex;
    span {
        width: 50px;
        line-height: 40px;
        text-align: center;
    }
    .search {
        width: 30%;
    }
}
.searchMain {
    height: 80px;
}
</style>
